package com.dongdongqiang.daogenerator.tablemetabuilder;

import com.dongdongqiang.daogenerator.pojo.TableColumn;
import com.dongdongqiang.daogenerator.pojo.TableMeta;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZZB on 2017/10/15.
 */
public class TableMetaContext {
    private static final Map<String, TableMeta> tableMetaCache = new HashMap<>();
    private static final Map<String, Map<String, TableColumn>> columnToFieldMap = new HashMap<>();
    private static final Map<String, Map<String, TableColumn>> fieldToColumnMap = new HashMap<>();

    public static TableMeta obtainByClazz(Class clazz) {
        String name = clazz.getName();
        return tableMetaCache.get(name);
    }

    public static boolean exist(Class clazz) {
        String name = clazz.getName();
        return tableMetaCache.containsKey(name);
    }

    public static void put(TableMeta tableMeta) {
        Class clazz = tableMeta.getBeanClass();
        tableMetaCache.put(clazz.getName(), tableMeta);
        List<TableColumn> tableColumns = tableMeta.getTableColumns();
        Map<String, TableColumn> columnToFieldMapEntry = new HashMap<>();
        Map<String, TableColumn> fieldToColumnMapEntry = new HashMap<>();
        for (TableColumn tableColumn : tableColumns) {
            columnToFieldMapEntry.put(tableColumn.getColumnName(), tableColumn);
            fieldToColumnMapEntry.put(tableColumn.getPropertyName(), tableColumn);
        }
        columnToFieldMap.put(clazz.getName(), columnToFieldMapEntry);
        fieldToColumnMap.put(clazz.getName(), fieldToColumnMapEntry);
    }

    public static TableColumn obtainByColumnName(Class clazz, String columnName) {
        Map<String, TableColumn> columnToFieldMapEntry = columnToFieldMap.get(clazz.getName());
        return columnToFieldMapEntry.get(columnName);
    }

    public static TableColumn obtainByFieldName(Class clazz, String fieldName) {
        Map<String, TableColumn> fieldToColumnMapEntry = fieldToColumnMap.get(clazz.getName());
        return fieldToColumnMapEntry.get(fieldName);
    }
}
